package vn.gq.udv.comic;

import java.util.ArrayList;

import vn.gq.udv.comic.fragment.ReaderFragment;
import vn.gq.udv.comic.model.item.ChapterItem;
import vn.gq.udv.tab.SwipeyTabs;
import vn.gq.udv.tab.SwipeyTabsAdapter;
import vn.gq.udv.utils.AdmobAdsHandler;
import vn.gq.udv.utils.ImageCache;
import vn.gq.udv.utils.ImageFetcher;
import vn.gq.udv.utils.NetworkUtils;
import vn.gq.udv.utils.ViewPager;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.res.Configuration;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentStatePagerAdapter;
import android.text.InputType;
import android.util.DisplayMetrics;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.WindowManager.LayoutParams;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.google.ads.AdView;


public class ReaderActivity extends FragmentActivity implements OnClickListener, IPagerActivity {

	public static final String EXTRA_LAST_PAGE_NUM = "extra_last_page_num";
	public static final String EXTRA_CHAPTER_IMAGES = "extra_chapter_images";
	public static final String EXTRA_CHAPTER_ITEM = "extra_chapter_item";
	
	private static final String IMAGE_CACHE_DIR = "images";
    public static final String EXTRA_IMAGE = "extra_image";
	
	private int mLastPagePos;
	private SwipeyTabs mTabs;
	private ViewPager mViewPager;
	private SwipeyTabsPagerAdapter mAdapter;
    private ImageFetcher mImageFetcher;
    private ArrayList<String> mData = new ArrayList<String>();
    private LinearLayout mMenuLayout;
    private ImageButton btnFirst, btnLast, btnGo;
    private ChapterItem mChapterItem;
    private AdmobAdsHandler mAdHandler;
    private Handler mHandler = new Handler();
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.image_detail_pager);
		NetworkUtils.newInstance(ReaderActivity.this).check();
		
		setupLayoutOnCreate();
		
		final DisplayMetrics displayMetrics = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getMetrics(displayMetrics);
        final int height = displayMetrics.heightPixels;
        final int width = displayMetrics.widthPixels;
        
        final int longest = (height > width ? height : width) / 2;
        
        ImageCache.ImageCacheParams cacheParams =
                new ImageCache.ImageCacheParams(this, IMAGE_CACHE_DIR);
        cacheParams.setMemCacheSizePercent(0.25f);
        mImageFetcher = new ImageFetcher(this, longest);
        mImageFetcher.addImageCache(getSupportFragmentManager(), cacheParams);
        mImageFetcher.setImageFadeIn(false);
        getWindow().addFlags(LayoutParams.FLAG_FULLSCREEN);
        menuInit();
	}
	
	public void setupLayoutOnCreate() {
		mAdHandler = new AdmobAdsHandler((AdView) findViewById(R.id.adView));
		mMenuLayout = (LinearLayout) findViewById(R.id.menu_read);
		mViewPager = (ViewPager) findViewById(R.id.pager);
		mViewPager.setPageMargin((int) getResources().getDimension(R.dimen.image_detail_pager_margin));
        mViewPager.setOffscreenPageLimit(3);
		mTabs = (SwipeyTabs) findViewById(R.id.swipeytabs);
		mLastPagePos = getIntent().getExtras().getInt(EXTRA_LAST_PAGE_NUM);
		mData = getIntent().getExtras().getStringArrayList(EXTRA_CHAPTER_IMAGES);
		mChapterItem = getIntent().getExtras().getParcelable(EXTRA_CHAPTER_ITEM);
		mAdapter = new SwipeyTabsPagerAdapter(this, getSupportFragmentManager());
		mViewPager.setAdapter(mAdapter);
		mTabs.setAdapter(mAdapter);
		mTabs.setAdmobAdsHandler(mAdHandler);
		mViewPager.setOnPageChangeListener(mTabs);
		mViewPager.setCurrentItem(mLastPagePos);
	}
	
	public void menuInit() {
		btnFirst = (ImageButton) findViewById(R.id.btnFirst);
		btnFirst.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				mViewPager.setCurrentItem(0);
			}
		});
        btnLast = (ImageButton) findViewById(R.id.btnLast);
        btnLast.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				if (mData.size()>0) {
					mViewPager.setCurrentItem(mData.size() - 1);
				}
			}
		});
        btnGo = (ImageButton) findViewById(R.id.btnGo);
        btnGo.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				AlertDialog.Builder builder = new Builder(ReaderActivity.this);
				final EditText edt = new EditText(getApplicationContext());
				edt.setTextColor(Color.BLACK);
				edt.setInputType(InputType.TYPE_CLASS_NUMBER);
				builder.setInverseBackgroundForced(true)
				.setMessage("Nhập số trang")
				.setCancelable(false)
				.setPositiveButton("OK", new DialogInterface.OnClickListener() {
					
					@Override
					public void onClick(DialogInterface dialog, int which) {
						int page = Integer.parseInt(edt.getText().toString());
						if (page > 0 && (page <= mData.size())) {
							mViewPager.setCurrentItem(page - 1);
						}
						dialog.dismiss();
					}
				})
				.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
					
					@Override
					public void onClick(DialogInterface dialog, int which) {
						dialog.dismiss();
					}
				})
				.setView(edt);
				
				
				builder.create().show();
			}
		});
	}
	
	@Override
	protected void onResume() {
		super.onResume();
		mAdHandler.loadAds();
		mImageFetcher.setExitTasksEarly(false);
	}

	@Override
	protected void onPause() {
		super.onPause();
		mImageFetcher.setExitTasksEarly(true);
        mImageFetcher.flushCache();
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		mImageFetcher.closeCache();
		mAdHandler.onDestroy();
	}

	@Override
	public void onConfigurationChanged(Configuration newConfig) {
		super.onConfigurationChanged(newConfig);
	}

	public ImageFetcher getImageFetcher() {
        return mImageFetcher;
    }

	public static void startActivity(Context context, ChapterItem cItem, ArrayList<String> chapterImages) {
		startActivity(context, cItem, chapterImages, 0);
	}
	
	public static void startActivity(Context context, ChapterItem cItem, ArrayList<String> chapterImages, int position) {
		Intent intent = new Intent(context, ReaderActivity.class);
		intent.putExtra(EXTRA_LAST_PAGE_NUM, position);
		intent.putExtra(EXTRA_CHAPTER_IMAGES, chapterImages);
		intent.putExtra(EXTRA_CHAPTER_ITEM, cItem);
		context.startActivity(intent);
	}
	
	private class SwipeyTabsPagerAdapter extends FragmentStatePagerAdapter implements
		SwipeyTabsAdapter {
		
		private final Context mContext;
		
		public SwipeyTabsPagerAdapter(Context context, FragmentManager fm) {
			super(fm);
			this.mContext = context;
		}
		
		@Override
		public Fragment getItem(int position) {
			return ReaderFragment.newInstance(mData.get(position), position);
		}
		
		@Override
		public int getCount() {
			return mData.size();
		}
		
		public TextView getTab(final int position, SwipeyTabs root) {
			TextView view = (TextView) LayoutInflater.from(mContext).inflate(
					R.layout.swipey_tab_indicator, root, false);
			view.setText(String.format("%d/%d", position+1, getCount()));
			view.setOnClickListener(new OnClickListener() {
				public void onClick(View v) {
					mViewPager.setCurrentItem(position);
				}
			});
			
			return view;
		}
	}
	
	
	private Runnable hideMenuButton = new Runnable() {
		
		@Override
		public void run() {
			mMenuLayout.setVisibility(View.GONE);
		}
	};

	@Override
	public void onClick(View v) {
		if (mMenuLayout.getVisibility() == View.GONE) {
			mMenuLayout.setVisibility(View.VISIBLE);
			mHandler.removeCallbacks(hideMenuButton);
			mHandler.postDelayed(hideMenuButton, 3000);
		} else {
			mMenuLayout.setVisibility(View.GONE);
		}
	}

	@Override
	public ViewPager getViewPager() {
		return mViewPager;
	}

	@Override
	public void onBackPressed() {
		super.onBackPressed();
		BookmarkHelper.newInstance(ReaderActivity.this).saveBookmark(mChapterItem, mViewPager.getCurrentItem());
	}
}
